package cn.blnp.net.flowable.boot.ext.aspect;

import cn.blnp.net.flowable.boot.annotations.TenantAnnotation;
import cn.blnp.net.flowable.boot.customer.flowable.holder.MultiTenantInfoHolder;
import cn.blnp.net.flowable.boot.utils.SpELKeyGeneratorUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * <h3>自定义租户ID切面实现</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/9 19:49
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class TenantAspect {

    private final MultiTenantInfoHolder multiTenantInfoHolder;

    @Pointcut("@annotation(cn.blnp.net.flowable.boot.annotations.TenantAnnotation)")
    public void tenantPoint() {
    }

    @Around("tenantPoint()")
    public Object tenantPointCut(ProceedingJoinPoint point) throws Throwable{
        //获取方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取切入方法的对象
        Method method = signature.getMethod();
        //获取方法上的AOP注解
        TenantAnnotation tenantAnnotation = method.getAnnotation(TenantAnnotation.class);
        //获取注解上的租户ID值
        String tenantIdKey = tenantAnnotation.tenantId();
        String tenantId = SpELKeyGeneratorUtil.generateKeyBySpEL(tenantIdKey, point.getArgs(), signature.getParameterNames());
        log.warn("租户已切换，当前租户ID为：{}", tenantId);
        //切换租户
        multiTenantInfoHolder.setCurrentTenantId(tenantId);
        try {
            return point.proceed();
        } finally {
            //清空租户
            multiTenantInfoHolder.clearCurrentTenantId();
            log.warn("租户已重置，当前租户ID为：{}", multiTenantInfoHolder.getCurrentTenantId());
        }
    }
}
